/**
 * Copyright(c) kyle.
 */
package algorithm;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/**
 * 找到不大于i的2的n次幂
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-27 23:24]
 * @since [2021-09-27 23:24]
 */
public class HighestOneBit {
    @DisplayName("找到不大于i的最大的2的n次幂")
    @Test
    public void testhighestOneBit() {
        int loop = 10000;
        for (int i = 0; i < loop; i++) {
            System.out.println(i + " --- " + Integer.highestOneBit(i));
            System.out.println(i + " --- " + highestOneBit(i));
            System.out.println(-i + " *** " + Integer.highestOneBit(-i));
            System.out.println(-i + " *** " + highestOneBit(-i));
        }
    }

    public static int highestOneBit(int i) {
        // HD, Figure 3-1
        i |= (i >>>  1);
        i |= (i >>>  2);
        i |= (i >>>  4);
        i |= (i >>>  8);
        i |= (i >>> 16);
        return i ^ (i >>> 1);
    }
}
